﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using Foothill.Common;
using Foothill.Common.Logging;

namespace Foothill.Service.UploadPhoto
{
    public class ImageProcessor : System.Web.UI.Page, IImageProcessor
    {
        // generate a thumbnail and return path of the generated image
        // the filename for thumbnail is the same as that for photo, but in a different folder
        public string GenerateThumbnail(int x, int y, string imgPath)
        {
            // Create the in-memory bitmap where you will draw the image.
            Bitmap bmp = new Bitmap(x, y);
            Graphics g = Graphics.FromImage(bmp);

            // make the high quality thumbnail
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;

            Image thumbnail;
            string pathToSave;

            // Load the file data.
            try
            {
                thumbnail = Image.FromFile(imgPath);

                // Draw the thumbnail.
                g.DrawImage(thumbnail, 0, 0, x, y);

                // the filename for thumbnail is the same as the photo's
                pathToSave = Server.MapPath(GlobalSettings.ThumbnailFolder) + "\\" + Path.GetFileName(imgPath);
                bmp.Save(pathToSave);
            }
            catch (Exception ex)
            {
                Log.Error(FoothillModule.Service, "Fail when creating an thumbnail", ex);
                throw;
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
            }

            return pathToSave;
        }
    }
}
